package com.bee.剑指offer;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Queue;

/**
 * 给定一个二叉树，返回该二叉树的之字形层序遍历，（第一层从左向右，下一层从右向左，一直这样交替）
 * 层序遍历，可以借助Queue队列
 */
public class 按之字形顺序打印二叉树 {

    public static ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<>();
        if (pRoot == null) {
            return result;
        }
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.offer(pRoot);
        // true 从左边往右边走，false从右边往左边走
        Boolean flag = true;
        while (!queue.isEmpty()) {
            int size = queue.size();
            ArrayList<Integer> list = new ArrayList<>();
            // 这一层的数据
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                // 在这里需要判断从左还是从右遍历
                list.add(poll.val);
                if (poll.left != null) {
                    queue.offer(poll.left);
                }
                if (poll.right != null) {
                    queue.offer(poll.right);
                }
            }
            if (!flag) {
                // 将元素倒过来
                ArrayList<Integer> temp = new ArrayList<>();
                for (int i = list.size() - 1; i >= 0; i--) {
                    temp.add(list.get(i));
                }
                list = temp;
                flag = true;
            } else {
                flag = false;
            }
            result.add(list);
        }
        return result;
    }

    public static void main(String[] args) {
        TreeNode head = new TreeNode(1);
        head.left = new TreeNode(2);
        head.right = new TreeNode(3);
        head.right.left = new TreeNode(4);
        head.right.right = new TreeNode(5);
        ArrayList<ArrayList<Integer>> print = Print(head);
        System.out.println(print.toString());
    }
}
